package com.LeeCode;

import java.util.HashMap;

/**
 * K 和数对的最大数目
 */

public class Code1679 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4};
        int k = 5;
        System.out.println(new Code1679().maxOperations(nums, k));
    }

    public int maxOperations(int[] nums, int k) {
        int ans = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            int target = k - num;
            if (map.containsKey(target)) {
                map.merge(target, -1, (oldVal, delta) -> {
                    int res = oldVal + delta;
                    return res == 0 ? null : res;
                });
                ans++;
            } else {
                map.merge(num, 1, Integer::sum);
            }
        }
        return ans;
    }
}
